﻿using System;
using System.Collections.Generic;
using System.Text;

using System.IO;
using System.Security.Cryptography;

namespace LinkUp
{
    /// <summary>
    /// 加密解密的安全类
    /// </summary>
    public class Safe
    {
        /// <summary>
        /// 加密字符串
        /// </summary>
        /// <param name="PlainText"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string Encrypt(string data, SymmetricAlgorithm key)
        {
            MemoryStream ms = new MemoryStream();
            CryptoStream encStream = new CryptoStream(ms, key.CreateEncryptor(byKey, IV), CryptoStreamMode.Write);
            StreamWriter sw = new StreamWriter(encStream);
            sw.Write(data);
            sw.Flush();
            encStream.FlushFinalBlock();
            sw.Flush();
            return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
        }

        /// <summary>
        /// 解密字符数组到字符串
        /// </summary>
        /// <param name="CypherText"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string Decrypt(string enData, SymmetricAlgorithm key)
        {
            byte[] byEnc;
            try
            {
                byEnc = Convert.FromBase64String(enData);
            }
            catch
            {
                return string.Empty;
            }
            MemoryStream ms = new MemoryStream(byEnc);
            CryptoStream encStream = new CryptoStream(ms, key.CreateDecryptor(byKey, IV), CryptoStreamMode.Read);
            StreamReader sr = new StreamReader(encStream);
            return sr.ReadToEnd();
        }

        #region field and property
        private static byte[] byKey = { 0xEF, 0xCD, 0xAB, 0x90, 0x78, 0x56, 0x34, 0x12 };
        private static byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
        #endregion
    }
}
